<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        width: 100px;
        height: 100px;
        background-color: green;
        position: absolute;
        top: 100px;
        left: 100px;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
    <script>
      const manageCookie = {
        set(name, value, date) {
          // expires date:传入的天数
          /* const endDate = new Date();
          endDate.setDate(endDate.getDate() + date);
          document.cookie = `${name}=${value}; expires=${endDate}`; */

          // max-age要求传入的秒数
          document.cookie = `${name}=${value}; max-age=${date}`;
        },
        remove(name) {
          this.set(name, "", 0);
        },
        get(name) {
          const cookies = document.cookie.split("; ");
          for (let i = 0; i < cookies.length; i++) {
            const [cookieName, value] = cookies[i].split("=");
            if (name === cookieName) {
              return value;
            }
          }
        },
      };

      const drag = {
        init(dom) {
          const left = manageCookie.get("newLeft");
          const top = manageCookie.get("newTop");
          this.dom = dom;
          this.bindEvent();

          this.dom.style.left = left ? left + "px" : "100px";
          this.dom.style.top = top ? top + "px" : "100px";
        },
        bindEvent() {
          this.dom.onmousedown = this.mouseDown.bind(this);
        },
        mouseDown(e) {
          document.onmousemove = this.mouseMove.bind(this);
          document.onmouseup = this.mouseUp.bind(this);
          this.disX = e.clientX - this.dom.offsetLeft;
          this.disY = e.clientY - this.dom.offsetTop;
        },
        mouseMove(e) {
          this.newLeft = e.clientX - this.disX;
          this.newTop = e.clientY - this.disY;
          this.dom.style.left = this.newLeft + "px";
          this.dom.style.top = this.newTop + "px";
        },
        mouseUp(e) {
          document.onmousemove = null;
          document.onmouseup = null;
          manageCookie.set("newLeft", this.newLeft, 10000);
          manageCookie.set("newTop", this.newTop, 10000);
        },
      };

      drag.init(document.querySelector("#box"));
    </script>
  </body>
</html>
